package com.grj.parkingsystem.controller;


import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.grj.parkingsystem.common.Result;
import com.grj.parkingsystem.dto.UserLoginDTO;
import com.grj.parkingsystem.dto.UserRegisterDTO;
import com.grj.parkingsystem.entity.User;
import com.grj.parkingsystem.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@RestController
@RequestMapping("/api/user")
@Api(tags = "1. 用户管理")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/register")
    @ApiOperation(value = "用户注册", notes = "创建新用户账号")
    @ApiOperationSupport(order = 1)
    public Result<?> register(@RequestBody @Valid UserRegisterDTO dto) {
        userService.register(dto.getUsername(), dto.getPassword(), dto.getPhone());
        return Result.success("注册成功");
    }

    @PostMapping("/login")
    @ApiOperation(value = "用户登录", notes = "用户登录并获取认证Token")
    @ApiOperationSupport(order = 2)
    public Result<?> login(@RequestBody @Valid UserLoginDTO dto) {
        Object result = userService.login(dto.getUsername(), dto.getPassword());
        return Result.success("登录成功", result);
    }

    @GetMapping("/info")
    @ApiOperation(value = "获取用户信息", notes = "根据Token获取当前用户信息")
    @ApiOperationSupport(order = 3)
    public Result<?> getUserInfo(@RequestHeader("Authorization") String token) {
        User user = userService.getUserInfo(token);
        return Result.success(user);
    }

    @PutMapping("/update")
    @ApiOperation(value = "更新用户信息", notes = "更新当前用户的基本信息")
    @ApiOperationSupport(order = 4)
    public Result<?> updateUser(@RequestBody User user, @RequestHeader("Authorization") String token) {
        userService.updateUser(user, token);
        return Result.success("更新成功");
    }
}    